'use strict';
import tools from './tools.js';
//import '../style/login.less';

const ursScript = 'https://webzj.reg.163.com/webapp/javascript/message.js';
const MAIN_HOST = 'http://localhost';

let ursConf = {
  product: `open`,
  promark: `hQvjXOs`,
  host: `open.163.com`,
  swidth: 295,
  frameSize: {
    width: 450,
    height: 450
  },
  single : 1,
  cssDomain: MAIN_HOST +'/static/style/',
  cssFiles: 'login_iframe.css'
};

let urs;
let defaultLogincb, logincb;
let logincbHandler = (data) => {
  logincb(data);
};

/**
 * 显示登录iframe
 */
let showHandler = () => {
  urs && urs.showIframe();
};
const setShowHandler = (Handler) => {
  showHandler = Handler;
};
const show = (callback) => {
  logincb = callback || defaultLogincb;
  showHandler();
};

/**
 * 隐藏登录iframe
 */
let hideHandler = () => {
  urs && urs.closeIframe();
};
const setHideHandler = (Handler) => {
  hideHandler = Handler;
};
const hide = () => {
  hideHandler();
};
/**
 * 注册登录成功回调，参数为用户名
 * @param  {Function} fn 要注册的回调函数
 */
let success = (fn) => { // 注册登录回调必须在ready之后
  ready.then(() => typeof fn === 'function' && (urs.logincb = fn));
};

/**
 * 初始化登入组件
 * @param includeBox
 * @param logincb
 */
let init = (includeBox, loginCallback) => {
  includeBox && (ursConf.includeBox = includeBox);
  logincb = loginCallback;
  defaultLogincb = loginCallback;
  ursConf.logincb = logincbHandler;
  return new Promise((resolve, reject) => {
    tools.importScript(ursScript+'?'+(Math.floor((+new Date)/100000))).then(() => {
      urs = new URS(ursConf);
      resolve('ready');
    }).catch(e => {
      reject(`urs script:${ursScript} import failed!`)
    });
  });
};
/**
 * 检测是否登入
 * @Deprecated
 * @returns {*|boolean}
 */
const checkLogin = () => {
  let S_Info = tools.cookie.getItem('S_INFO');
  let P_Info = tools.cookie.getItem('P_INFO') || '';
  let S_OInfo = tools.cookie.getItem('S_OINFO');
  let P_OInfo = tools.cookie.getItem('P_OINFO') || '';
  return (S_Info && P_Info.split('|')[2] !== '2') || (S_OInfo && P_OInfo.split('|')[2] !== '2');
};
/**
 * 获取用户信息
 * @Deprecated
 * @returns {{mail: *, nickname: *, logined: (*|boolean), thirdLogin: boolean}}
 */
const getUserInfo = () => {
  let S_Info = tools.cookie.getItem('S_INFO') || '';
  let P_Info = tools.cookie.getItem('P_INFO') || '';
  let S_OInfo = tools.cookie.getItem('S_OINFO') || '';
  let P_OInfo = tools.cookie.getItem('P_OINFO') || '';
  var thirdLogin = !!(S_OInfo && P_OInfo);
  return {
    mail: !thirdLogin ? P_Info.split('|')[0] : P_OInfo.split('|')[0],
    nickname: S_Info.split('|')[3] || S_OInfo.split('|')[3],
    loggedIn: checkLogin(),
    thirdLogin: thirdLogin
  };
};

let userInfo = getUserInfo();

export default {
  init,
  show,
  setShowHandler,
  hide,
  setHideHandler,
  success,
  checkLogin,
  getUserInfo,
  userInfo
};
